using Microsoft.NetEnterpriseServers;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Sdk.Sfc;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.SqlManagerUI.Scripting;
using Microsoft.SqlServer.Management.SqlMgmt;
using Microsoft.SqlServer.Management.UI;
using Microsoft.SqlServer.Management.UI.VSIntegration;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Net;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security;
using System.Threading;
using System.Windows.Forms;
using System.Xml;
using System.Xml.XPath;

namespace Microsoft.SqlServer.Management.SqlManagerUI
{
	[ComVisible(false)]
	public class GenScriptWizForm : KomodoWizardForm
	{
		public enum ScriptWizardPage
		{
			Server,
			Database,
			ObjectTypes,
			ApplicationRoles,
			Assemblies,
			DatabaseTriggers,
			DatabaseRoles,
			Defaults,
			Rules,
			Schemas,
			StoredProcedures,
			Synonyms,
			Tables,
			UserDefinedDataTypes,
			UserDefinedFunctions,
			UserDefinedAggregate,
			UserDefinedType,
			Users,
			Views,
			XmlSchemaCollections,
			FullTextCatalog,
			OutputOptions,
			ScriptOptions,
			Finish,
			Count
		}

		private delegate void ScriptToWindowEventHandler(string text);

		private delegate void ScriptToClipboardEventHandler(string text);

		private IServiceProvider serviceProvider;

		private CDataContainer dataContainer;

		private GenerateScriptMaker scriptMaker;

		private IMessageBoxProvider messageProvider;

		private ProgressReportWizardPage progressPage;

		private GenWizGeneralData generalData;

		private List<GenWizObjectType> objectTypeList;

		private ServerConnection smoConnection;

		private object smoConnectionLock = new object();

		private Dictionary<int, int> urnProgressDictionary = new Dictionary<int, int>();

		private int currentStep;

		private bool hasObjectInformation;

		private bool isAborted;

		private List<string> _actions;

		private int _actionIndex;

		private GenScriptWizForm.ScriptWizardPage firstObjectPage = GenScriptWizForm.ScriptWizardPage.ApplicationRoles;

		private GenScriptWizForm.ScriptWizardPage lastObjectPage = GenScriptWizForm.ScriptWizardPage.FullTextCatalog;

		private List<WizardPage> wizPages = new List<WizardPage>();

		public IScriptingOptions ShellScriptingOptions
		{
			get
			{
				IScriptingOptions result = null;
				if (this.serviceProvider != null)
				{
					result = (this.serviceProvider.GetService(typeof(IScriptingOptions)) as IScriptingOptions);
				}
				return result;
			}
		}

		public IMessageBoxProvider MessageProvider
		{
			get
			{
				return this.messageProvider;
			}
		}

		protected override void Dispose(bool disposing)
		{
			if (disposing)
			{
				if (this.dataContainer != null)
				{
					this.dataContainer.Dispose();
					this.dataContainer = null;
				}
				if (this.wizPages != null)
				{
					foreach (WizardPage current in this.wizPages)
					{
						IDisposable disposable = current;
						if (disposable != null)
						{
							disposable.Dispose();
						}
					}
					this.wizPages = null;
				}
			}
			base.Dispose(disposing);
			if (base.ProgressPage != null && !base.ProgressPage.IsDisposed)
			{
				base.ProgressPage.Dispose();
				base.ProgressPage = null;
			}
		}

		public void ScriptToWindow(string text)
		{
			if (!base.InvokeRequired)
			{
				this.ScriptToWindowInt(text);
				return;
			}
			base.Invoke(new GenScriptWizForm.ScriptToWindowEventHandler(this.ScriptToWindowInt), new object[]
			{
				text
			});
		}

		private void ScriptToWindowInt(string text)
		{
			ILaunchFormHost launchFormHost = (ILaunchFormHost)this.serviceProvider.GetService(typeof(ILaunchFormHost));
			launchFormHost.ScriptToNewWindow(text, "sql");
		}

		public void ScriptToClipboard(string text)
		{
			if (!base.InvokeRequired)
			{
				this.ScriptToClipboardInt(text);
				return;
			}
			base.Invoke(new GenScriptWizForm.ScriptToClipboardEventHandler(this.ScriptToClipboardInt), new object[]
			{
				text
			});
		}

		private void ScriptToClipboardInt(string text)
		{
			ILaunchFormHost launchFormHost = (ILaunchFormHost)this.serviceProvider.GetService(typeof(ILaunchFormHost));
			launchFormHost.ScriptToClipboard(text, "sql");
		}

		public bool CanEnableFinish()
		{
			bool result = false;
			foreach (GenWizObjectType current in this.objectTypeList)
			{
				if (current.IsSelected)
				{
					if (current.SelectedUrns.Count == 0)
					{
						result = false;
						break;
					}
					result = true;
				}
			}
			return result;
		}

		public GenScriptWizForm()
		{
		}

		public GenScriptWizForm(IXPathNavigable doc, IServiceProvider site)
		{
			this.InitializeForm(doc, site);
		}

		public GenScriptWizForm(IXPathNavigable doc, IServiceProvider site, string connectionString)
		{
			this.InitializeForm(doc, site);
			SelectServerWizardPage selectServerWizardPage = this.wizPages[0] as SelectServerWizardPage;
			if (selectServerWizardPage != null)
			{
				selectServerWizardPage.ConnectionString = connectionString;
				if (selectServerWizardPage.ValidateForm())
				{
					this.FirstPage = this.wizPages[1];
					base.WizardInputs.AddEditItem(1, new GenWizTransferOptions(this.generalData.SqlServerVersion));
				}
			}
		}

		private void InitializeForm(IXPathNavigable doc, IServiceProvider site)
		{
			if (site == null)
			{
				throw new ArgumentNullException("site");
			}
			this.serviceProvider = site;
			base.WizardInputs = new WizardInputs();
			this.dataContainer = new CDataContainer();
			if (doc != null)
			{
				this.dataContainer.Init((XmlDocument)doc, site);
			}
			this.messageProvider = (IMessageBoxProvider)site.GetService(typeof(IMessageBoxProvider));
			if (this.messageProvider == null)
			{
				AssemblyName assemblyRef = new AssemblyName("sqlmgmt, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91, processorArchitecture=MSIL");
				Assembly assembly = Assembly.Load(assemblyRef);
				Type type = assembly.GetType("Microsoft.SqlServer.Management.SqlMgmt.DefaultMessageBoxProvider");
				ConstructorInfo constructor = type.GetConstructor(new Type[]
				{
					typeof(Control)
				});
				object obj = constructor.Invoke(new object[]
				{
					this
				});
				this.messageProvider = (IMessageBoxProvider)obj;
			}
			this.generalData = new GenWizGeneralData(this.dataContainer);
			base.WizardInputs.AddItem(0, this.generalData);
			base.WizardInputs.AddItem(1, null);
			this.objectTypeList = new List<GenWizObjectType>();
			base.WizardInputs.AddItem(2, this.objectTypeList);
			for (GenScriptWizForm.ScriptWizardPage scriptWizardPage = this.firstObjectPage; scriptWizardPage <= this.lastObjectPage; scriptWizardPage++)
			{
				this.AddObjectTypeToList(scriptWizardPage, this.objectTypeList);
			}
			this.InitializeComponent();
			this.Text = GenScriptWizSR.WizardText("");
			this.TitleCaption = GenScriptWizSR.TitleCaption;
			this.TitleText = GenScriptWizSR.TitleText;
			base.ShowInTaskbar = true;
			this.HelpFile = "ms-help://MS.SQLCC";
			base.TitleHelpTopicKeyword = "sql9.swb.generatescriptswizard.welcome.f1";
			Bitmap glyph = CUtils.LoadBitmap("genscriptwizheader.bmp");
			this.TitleGlyph = CUtils.LoadBitmap("genscriptwizwelc.bmp");
			base.Icon = CUtils.LoadIcon("server.ico");
			try
			{
				base.ShowTitlePageFromTitleCheckBox = true;
				base.TitleCheckBoxRegistryKey = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Microsoft SQL Server\\90\\Tools\\PublishingWizard");
				base.TitleCheckBoxRegistryValue = "ShowTitleInDPW";
			}
			catch (SecurityException)
			{
			}
			catch (ArgumentNullException)
			{
			}
			catch (ArgumentException)
			{
			}
			catch (ObjectDisposedException)
			{
			}
			catch (UnauthorizedAccessException)
			{
			}
			catch (IOException)
			{
			}
			this.wizPages.Add(new SelectServerWizardPage(this));
			this.wizPages.Add(new SelectDatabaseWizardPage(this));
			this.wizPages.Add(new PickObjectTypesWizardPage(this));
			this.wizPages.Add(new OutputOptionsWizardPage(this));
			this.wizPages.Add(new ScriptOptionsWizardPage(this));
			this.wizPages.Add(new GenScriptFinishWizardPage(this));
			this.FirstPage = this.wizPages[0];
			base.LastPage = this.wizPages[this.wizPages.Count - 1];
			this.FinishEnabled = false;
			this.BackEnabled = false;
			base.EnableFinishAutomatically = false;
			this.FirstPage.Back = null;
			WizardPage back = null;
			for (int i = 0; i < this.wizPages.Count; i++)
			{
				WizardPage wizardPage = this.wizPages[i];
				wizardPage.Back = back;
				if (i < this.wizPages.Count - 1)
				{
					wizardPage.Next = this.wizPages[i + 1];
				}
				wizardPage.Glyph = glyph;
				back = wizardPage;
			}
			base.ProgressPage = new ProgressReportWizardPage(this);
			this.progressPage = (ProgressReportWizardPage)base.ProgressPage;
			this.progressPage.ShowBackOnIncompleteOperation = false;
			this.progressPage.Glyph = CUtils.LoadBitmap("genscriptwizsummary.bmp");
			this.progressPage.LeftAlignedGlyph = false;
			this.progressPage.HelpTopicKeyword = "sql9.swb.generatescriptswizard.progress.f1";
		}

		public bool ValidateFileInfo()
		{
			bool flag = true;
			GenWizOptionsBase genWizOptionsBase = (GenWizOptionsBase)base.WizardInputs.FindItem(1);
			if (this.generalData.SaveScriptDestination == GenWizGeneralData.ScriptDestination.ToSingleFile && !this.generalData.FileInfoValidated)
			{
				if (File.Exists(this.generalData.SaveFileName))
				{
					if (this.generalData.OverwriteExistingFile)
					{
						this.generalData.ScriptingDriver.OverwriteExisting = true;
						goto IL_1BF;
					}
					if (genWizOptionsBase.AppendToFile)
					{
						goto IL_1BF;
					}
					if (this.MessageProvider.ShowMessage(GenScriptWizSR.GenerateScriptFileExists(this.generalData.SaveFileName), GenScriptWizSR.WizardText(""), ExceptionMessageBoxButtons.YesNo, ExceptionMessageBoxSymbol.Question, this) == DialogResult.No)
					{
						flag = false;
						this.generalData.ScriptingDriver.OverwriteExisting = false;
						this.generalData.OverwriteExistingFile = false;
						goto IL_1BF;
					}
					this.generalData.ScriptingDriver.OverwriteExisting = true;
					this.generalData.OverwriteExistingFile = true;
					goto IL_1BF;
				}
				else
				{
					try
					{
						try
						{
							using (FileStream fileStream = File.Create(this.generalData.SaveFileName))
							{
								fileStream.WriteByte(1);
								fileStream.Close();
							}
						}
						catch (Exception)
						{
							this.MessageProvider.ShowMessage(GenScriptWizSR.GenarateScriptInvalidFile(this.generalData.SaveFileName), GenScriptWizSR.WizardText(""), ExceptionMessageBoxButtons.OK, ExceptionMessageBoxSymbol.Warning, this);
							flag = false;
						}
						goto IL_1BF;
					}
					finally
					{
						if (File.Exists(this.generalData.SaveFileName))
						{
							File.Delete(this.generalData.SaveFileName);
						}
					}
				}
			}
			if (this.generalData.SaveScriptDestination == GenWizGeneralData.ScriptDestination.ToFilePerObject && !this.generalData.FileInfoValidated && !Directory.Exists(this.generalData.SaveFileName))
			{
				this.MessageProvider.ShowMessage(GenScriptWizSR.GenerateScriptInvalidDirectory(this.generalData.SaveFileName), GenScriptWizSR.WizardText(""), ExceptionMessageBoxButtons.OK, ExceptionMessageBoxSymbol.Warning, this);
				flag = false;
			}
			IL_1BF:
			this.generalData.FileInfoValidated = flag;
			return flag;
		}

		private void AddObjectTypeToList(GenScriptWizForm.ScriptWizardPage curPage, List<GenWizObjectType> ObjectTypeList)
		{
			switch (curPage)
			{
			case GenScriptWizForm.ScriptWizardPage.ApplicationRoles:
				ObjectTypeList.Add(new GenWizObjectType
				{
					PageId = GenScriptWizForm.ScriptWizardPage.ApplicationRoles,
					PageTitle = GenScriptWizSR.GenScriptSelectAppRoleFormTitle,
					PageSubTitle = GenScriptWizSR.GenScriptSelectAppRoleFormSubtitle,
					HelpTopicKeyword = "sql9.swb.generatescriptswizard.chooseobjects.f1",
					PageDescription = GenScriptWizSR.GenScriptSelectAppRoleFormGridLabel,
					SchemaBased = false,
					WizardInputs = base.WizardInputs,
					FriendlyName = GenScriptWizSR.GenScriptObjectTypeRadioAppRole,
					EnumeratorPath = "ApplicationRole"
				});
				return;
			case GenScriptWizForm.ScriptWizardPage.Assemblies:
				ObjectTypeList.Add(new GenWizObjectType
				{
					PageId = GenScriptWizForm.ScriptWizardPage.Assemblies,
					PageTitle = GenScriptWizSR.GenScriptSelectAssembliesFormTitle,
					PageSubTitle = GenScriptWizSR.GenScriptSelectAssembliesFormSubtitle,
					HelpTopicKeyword = "sql9.swb.generatescriptswizard.chooseobjects.f1",
					PageDescription = GenScriptWizSR.GenScriptSelectAssembliesFormGridLabel,
					SchemaBased = false,
					WizardInputs = base.WizardInputs,
					FriendlyName = GenScriptWizSR.GenScriptObjectTypeRadioAssemblies,
					EnumeratorPath = "SqlAssembly",
					MinimumSupportedVersion = 9,
					SmoType = typeof(SqlAssembly)
				});
				return;
			case GenScriptWizForm.ScriptWizardPage.DatabaseTriggers:
				ObjectTypeList.Add(new GenWizObjectType
				{
					PageId = GenScriptWizForm.ScriptWizardPage.DatabaseTriggers,
					PageTitle = GenScriptWizSR.GenScriptSelectDatabaseTriggersFormTitle,
					PageSubTitle = GenScriptWizSR.GenScriptSelectDatabaseTriggersFormSubtitle,
					HelpTopicKeyword = "sql9.swb.generatescriptswizard.chooseobjects.f1",
					PageDescription = GenScriptWizSR.GenScriptSelectDatabaseTriggersFormGridLabel,
					SchemaBased = false,
					WizardInputs = base.WizardInputs,
					FriendlyName = GenScriptWizSR.GenScriptObjectTypeRadioDatabaseTriggers,
					EnumeratorPath = "DdlTrigger[@IsSystemObject=false()]",
					MinimumSupportedVersion = 9
				});
				return;
			case GenScriptWizForm.ScriptWizardPage.DatabaseRoles:
				ObjectTypeList.Add(new GenWizObjectType
				{
					PageId = GenScriptWizForm.ScriptWizardPage.DatabaseRoles,
					PageTitle = GenScriptWizSR.GenScriptSelectDatabaseRolesFormTitle,
					PageSubTitle = GenScriptWizSR.GenScriptSelectDatabaseRolesFormSubtitle,
					HelpTopicKeyword = "sql9.swb.generatescriptswizard.chooseobjects.f1",
					PageDescription = GenScriptWizSR.GenScriptSelectDatabaseRolesFormGridLabel,
					SchemaBased = false,
					WizardInputs = base.WizardInputs,
					FriendlyName = GenScriptWizSR.GenScriptObjectTypeRadioDatabaseRoles,
					EnumeratorPath = "Role[@IsFixedRole = false() and @Name != 'public']"
				});
				return;
			case GenScriptWizForm.ScriptWizardPage.Defaults:
				ObjectTypeList.Add(new GenWizObjectType
				{
					PageId = GenScriptWizForm.ScriptWizardPage.Defaults,
					PageTitle = GenScriptWizSR.GenScriptSelectDefaultFormTitle,
					PageSubTitle = GenScriptWizSR.GenScriptSelectDefaultFormSubtitle,
					HelpTopicKeyword = "sql9.swb.generatescriptswizard.choosedefaults.f1",
					PageDescription = GenScriptWizSR.GenScriptSelectDefaultFormGridLabel,
					SchemaBased = true,
					WizardInputs = base.WizardInputs,
					FriendlyName = GenScriptWizSR.GenScriptObjectTypeRadioDefaults,
					EnumeratorPath = "Default",
					SmoType = typeof(Default)
				});
				return;
			case GenScriptWizForm.ScriptWizardPage.Rules:
				ObjectTypeList.Add(new GenWizObjectType
				{
					PageId = GenScriptWizForm.ScriptWizardPage.Rules,
					PageTitle = GenScriptWizSR.GenScriptSelectRulesFormTitle,
					PageSubTitle = GenScriptWizSR.GenScriptSelectRulesFormSubtitle,
					HelpTopicKeyword = "sql9.swb.generatescriptswizard.chooserules.f1",
					PageDescription = GenScriptWizSR.GenScriptSelectRulesFormGridLabel,
					SchemaBased = true,
					WizardInputs = base.WizardInputs,
					FriendlyName = GenScriptWizSR.GenScriptObjectTypeRadioRules,
					EnumeratorPath = "Rule",
					SmoType = typeof(Rule)
				});
				return;
			case GenScriptWizForm.ScriptWizardPage.Schemas:
				ObjectTypeList.Add(new GenWizObjectType
				{
					PageId = GenScriptWizForm.ScriptWizardPage.Schemas,
					PageTitle = GenScriptWizSR.GenScriptSelectSchemaFormTitle,
					PageSubTitle = GenScriptWizSR.GenScriptSelectSchemaFormSubtitle,
					HelpTopicKeyword = "sql9.swb.generatescriptswizard.chooseobjects.f1",
					PageDescription = GenScriptWizSR.GenScriptSelectSchemaFormGridLabel,
					SchemaBased = false,
					WizardInputs = base.WizardInputs,
					FriendlyName = GenScriptWizSR.GenScriptObjectTypeRadioSchema,
					EnumeratorPath = "Schema[(@ID > 4 and @ID < 16384) or (@ID > 16400)]",
					MinimumSupportedVersion = 9
				});
				return;
			case GenScriptWizForm.ScriptWizardPage.StoredProcedures:
				ObjectTypeList.Add(new GenWizObjectType
				{
					PageId = GenScriptWizForm.ScriptWizardPage.StoredProcedures,
					PageTitle = GenScriptWizSR.GenScriptSelectSPFormTitle,
					PageSubTitle = GenScriptWizSR.GenScriptSelectSPFormSubtitle,
					HelpTopicKeyword = "sql9.swb.generatescriptswizard.choosestoredprocedures.f1",
					PageDescription = GenScriptWizSR.GenScriptSelectSPFormGridLabel,
					SchemaBased = true,
					WizardInputs = base.WizardInputs,
					FriendlyName = GenScriptWizSR.GenScriptObjectTypeRadioSP,
					EnumeratorPath = "StoredProcedure[@IsSystemObject=false()]",
					SmoType = typeof(StoredProcedure)
				});
				return;
			case GenScriptWizForm.ScriptWizardPage.Synonyms:
				ObjectTypeList.Add(new GenWizObjectType
				{
					PageId = GenScriptWizForm.ScriptWizardPage.Synonyms,
					PageTitle = GenScriptWizSR.GenScriptSelectSynonymsFormTitle,
					PageSubTitle = GenScriptWizSR.GenScriptSelectSynonymsFormSubtitle,
					HelpTopicKeyword = "sql9.swb.generatescriptswizard.chooseobjects.f1",
					PageDescription = GenScriptWizSR.GenScriptSelectSynonymsFormGridLabel,
					SchemaBased = true,
					WizardInputs = base.WizardInputs,
					FriendlyName = GenScriptWizSR.GenScriptObjectTypeRadioSynonyms,
					EnumeratorPath = "Synonym",
					MinimumSupportedVersion = 9
				});
				return;
			case GenScriptWizForm.ScriptWizardPage.Tables:
				ObjectTypeList.Add(new GenWizObjectType
				{
					PageId = GenScriptWizForm.ScriptWizardPage.Tables,
					PageTitle = GenScriptWizSR.GenScriptSelectTablesFormTitle,
					PageSubTitle = GenScriptWizSR.GenScriptSelectTablesFormSubtitle,
					HelpTopicKeyword = "sql9.swb.generatescriptswizard.choosetables.f1",
					PageDescription = GenScriptWizSR.GenScriptSelectTablesFormGridLabel,
					SchemaBased = true,
					WizardInputs = base.WizardInputs,
					FriendlyName = GenScriptWizSR.GenScriptObjectTypeRadioTables,
					EnumeratorPath = "Table[@IsSystemObject=false()]",
					SmoType = typeof(Table)
				});
				return;
			case GenScriptWizForm.ScriptWizardPage.UserDefinedDataTypes:
				ObjectTypeList.Add(new GenWizObjectType
				{
					PageId = GenScriptWizForm.ScriptWizardPage.UserDefinedDataTypes,
					PageTitle = GenScriptWizSR.GenScriptSelectUDDTFormTitle,
					PageSubTitle = GenScriptWizSR.GenScriptSelectUDDTFormSubtitle,
					HelpTopicKeyword = "sql9.swb.generatescriptswizard.chooseuddt.f1",
					PageDescription = GenScriptWizSR.GenScriptSelectUDDTFormGridLabel,
					SchemaBased = true,
					WizardInputs = base.WizardInputs,
					FriendlyName = GenScriptWizSR.GenScriptObjectTypeRadioUDDT,
					EnumeratorPath = "UserDefinedDataType"
				});
				return;
			case GenScriptWizForm.ScriptWizardPage.UserDefinedFunctions:
				ObjectTypeList.Add(new GenWizObjectType
				{
					PageId = GenScriptWizForm.ScriptWizardPage.UserDefinedFunctions,
					PageTitle = GenScriptWizSR.GenScriptSelectUDFFormTitle,
					PageSubTitle = GenScriptWizSR.GenScriptSelectUDFFormSubtitle,
					HelpTopicKeyword = "sql9.swb.generatescriptswizard.chooseudf.f1",
					PageDescription = GenScriptWizSR.GenScriptSelectUDFFormGridLabel,
					SchemaBased = true,
					WizardInputs = base.WizardInputs,
					FriendlyName = GenScriptWizSR.GenScriptObjectTypeRadioUDF,
					EnumeratorPath = "UserDefinedFunction[@IsSystemObject=false()]",
					SmoType = typeof(UserDefinedFunction)
				});
				return;
			case GenScriptWizForm.ScriptWizardPage.UserDefinedAggregate:
				ObjectTypeList.Add(new GenWizObjectType
				{
					PageId = GenScriptWizForm.ScriptWizardPage.UserDefinedAggregate,
					PageTitle = GenScriptWizSR.GenScriptSelectUserDefinedAggregateFormTitle,
					PageSubTitle = GenScriptWizSR.GenScriptSelectUserDefinedAggregateFormSubtitle,
					HelpTopicKeyword = "sql9.swb.generatescriptswizard.chooseobjects.f1",
					PageDescription = GenScriptWizSR.GenScriptSelectUserDefinedAggregateFormGridLabel,
					SchemaBased = true,
					WizardInputs = base.WizardInputs,
					FriendlyName = GenScriptWizSR.GenScriptObjectTypeRadioUserDefinedAggregate,
					EnumeratorPath = "UserDefinedAggregate",
					MinimumSupportedVersion = 9
				});
				return;
			case GenScriptWizForm.ScriptWizardPage.UserDefinedType:
				ObjectTypeList.Add(new GenWizObjectType
				{
					PageId = GenScriptWizForm.ScriptWizardPage.UserDefinedType,
					PageTitle = GenScriptWizSR.GenScriptSelectUserDefinedTypeFormTitle,
					PageSubTitle = GenScriptWizSR.GenScriptSelectUserDefinedTypeFormSubtitle,
					HelpTopicKeyword = "sql9.swb.generatescriptswizard.chooseobjects.f1",
					PageDescription = GenScriptWizSR.GenScriptSelectUserDefinedTypeFormGridLabel,
					SchemaBased = true,
					WizardInputs = base.WizardInputs,
					FriendlyName = GenScriptWizSR.GenScriptObjectTypeRadioUserDefinedType,
					EnumeratorPath = "UserDefinedType",
					MinimumSupportedVersion = 9
				});
				return;
			case GenScriptWizForm.ScriptWizardPage.Users:
				ObjectTypeList.Add(new GenWizObjectType
				{
					PageId = GenScriptWizForm.ScriptWizardPage.Users,
					PageTitle = GenScriptWizSR.GenScriptSelectUsersFormTitle,
					PageSubTitle = GenScriptWizSR.GenScriptSelectUsersFormSubtitle,
					HelpTopicKeyword = "sql9.swb.generatescriptswizard.chooseobjects.f1",
					PageDescription = GenScriptWizSR.GenScriptSelectUsersFormGridLabel,
					SchemaBased = false,
					WizardInputs = base.WizardInputs,
					FriendlyName = GenScriptWizSR.GenScriptObjectTypeRadioUsers,
					EnumeratorPath = "User[@IsSystemObject=false()]",
					SmoType = typeof(User)
				});
				return;
			case GenScriptWizForm.ScriptWizardPage.Views:
				ObjectTypeList.Add(new GenWizObjectType
				{
					PageId = GenScriptWizForm.ScriptWizardPage.Views,
					PageTitle = GenScriptWizSR.GenScriptSelectViewFormTitle,
					PageSubTitle = GenScriptWizSR.GenScriptSelectViewFormSubtitle,
					HelpTopicKeyword = "sql9.swb.generatescriptswizard.chooseviews.f1",
					PageDescription = GenScriptWizSR.GenScriptSelectViewFormGridLabel,
					SchemaBased = true,
					WizardInputs = base.WizardInputs,
					FriendlyName = GenScriptWizSR.GenScriptObjectTypeRadioViews,
					EnumeratorPath = "View[@IsSystemObject=false()]",
					SmoType = typeof(Microsoft.SqlServer.Management.Smo.View)
				});
				return;
			case GenScriptWizForm.ScriptWizardPage.XmlSchemaCollections:
				ObjectTypeList.Add(new GenWizObjectType
				{
					PageId = GenScriptWizForm.ScriptWizardPage.XmlSchemaCollections,
					PageTitle = GenScriptWizSR.GenScriptSelectXMLSchemaFormTitle,
					PageSubTitle = GenScriptWizSR.GenScriptSelectXMLSchemaFormSubtitle,
					HelpTopicKeyword = "sql9.swb.generatescriptswizard.chooseobjects.f1",
					PageDescription = GenScriptWizSR.GenScriptSelectXMLSchemaFormGridLabel,
					SchemaBased = false,
					WizardInputs = base.WizardInputs,
					FriendlyName = GenScriptWizSR.GenScriptObjectTypeRadioXMLSchema,
					EnumeratorPath = "XmlSchemaCollection",
					MinimumSupportedVersion = 9,
					SmoType = typeof(XmlSchemaCollection)
				});
				return;
			case GenScriptWizForm.ScriptWizardPage.FullTextCatalog:
				ObjectTypeList.Add(new GenWizObjectType
				{
					PageId = GenScriptWizForm.ScriptWizardPage.FullTextCatalog,
					PageTitle = GenScriptWizSR.GenScriptSelectFullTextCatalogFormTitle,
					PageSubTitle = GenScriptWizSR.GenScriptSelectFullTextCatalogFormSubtitle,
					HelpTopicKeyword = "sql9.swb.generatescriptswizard.chooseobjects.f1",
					PageDescription = GenScriptWizSR.GenScriptSelectFullTextCatalogFormGridLabel,
					SchemaBased = false,
					WizardInputs = base.WizardInputs,
					FriendlyName = GenScriptWizSR.GenScriptObjectTypeRadioFullTextCatalog,
					EnumeratorPath = "FullTextCatalog",
					MinimumSupportedVersion = 9
				});
				return;
			default:
				return;
			}
		}

		public override void OnNextWizardPage(WizardPage page)
		{
			if (page == null)
			{
				throw new ArgumentNullException("page");
			}
			if (page.PageID == 2)
			{
				((PickObjectTypesWizardPage)page).AddRemovePages();
			}
		}

		internal void AddPage(WizardPage wizPage, int addPageId, int currentPageId)
		{
			for (WizardPage wizardPage = this.wizPages[currentPageId]; wizardPage != null; wizardPage = wizardPage.Next)
			{
				if (wizardPage.PageID == addPageId)
				{
					wizPage = null;
					break;
				}
				if (wizardPage.Next.PageID > addPageId)
				{
					WizardPage next = wizardPage.Next;
					wizardPage.Next = wizPage;
					wizPage.Back = wizardPage;
					wizPage.Next = next;
					next.Back = wizPage;
					break;
				}
			}
			this.wizPages.Add(wizPage);
		}

		internal void RemovePage(int pageId)
		{
			WizardPage wizardPage = null;
			foreach (WizardPage current in this.wizPages)
			{
				if (current != null && current.PageID == pageId)
				{
					wizardPage = current;
					current.Next.Back = current.Back;
					current.Back.Next = current.Next;
					break;
				}
			}
			if (wizardPage != null)
			{
				this.wizPages.Remove(wizardPage);
			}
		}

		public void Script()
		{
			OperationStatus result = OperationStatus.Success;
			try
			{
				this.smoConnection = this.generalData.ServerObject.ConnectionContext;
				this.generalData.ScriptingDriver.ProgressEvent = new EventHandler<ProgressEventArgs>(this.ScriptProgressEvent);
				if (this.scriptMaker.ScriptAllObjects)
				{
					this._actions.Add(ScriptingEngineResources.IncludeDefaultObjects);
				}
				if (this.generalData.SaveScriptDestination == GenWizGeneralData.ScriptDestination.ToSingleFile)
				{
					this._actions.Add(ScriptingEngineResources.ScriptingObjects);
					this._actions.Add(ScriptingEngineResources.WritingToFile.Trim());
				}
				else if (this.generalData.SaveScriptDestination == GenWizGeneralData.ScriptDestination.ToProvider)
				{
					this._actions.Add(ScriptingEngineResources.ConnectingToWebService);
					this._actions.Add(ScriptingEngineResources.ScriptingObjects);
					this._actions.Add(ScriptingEngineResources.PublishingToWebService);
				}
				for (int i = 0; i < this._actions.Count; i++)
				{
					string description = this._actions[i];
					if (i == 0)
					{
						this.progressPage.UpdateActionDescription(0, description);
					}
					else
					{
						this.progressPage.AddAction(description);
					}
				}
				this.currentStep = 0;
				this._actionIndex = 0;
				this.scriptMaker.DoScript();
				int num = this._actions.Count - 1;
				this.progressPage.UpdateActionDescription(num, this._actions[num]);
				this.progressPage.UpdateActionStatus(num, ProgressStatus.Success);
			}
			catch (PropertyCannotBeRetrievedException ex)
			{
				if (this.isAborted)
				{
					this.UpdateProgressWithAbort();
				}
				else
				{
					this.UpdateProgressFromSmoException(ex, ex.FailedObject);
				}
				result = OperationStatus.Error;
			}
			catch (FailedOperationException ex2)
			{
				if (this.isAborted)
				{
					this.UpdateProgressWithAbort();
				}
				else
				{
					this.UpdateProgressFromSmoException(ex2, ex2.FailedObject);
				}
				result = OperationStatus.Error;
			}
			catch (WebException ex4)
			{
				if (this.isAborted)
				{
					this.UpdateProgressWithAbort();
				}
				else
				{
					int actionIndex = this.UpdateProgressStatus(null, ProgressStatus.Error);
					Exception ex3 = null;
					if (ex4.Response is HttpWebResponse)
					{
						HttpWebResponse httpWebResponse = ex4.Response as HttpWebResponse;
						HttpStatusCode statusCode = httpWebResponse.StatusCode;
						if (statusCode != HttpStatusCode.Unauthorized)
						{
							if (statusCode == HttpStatusCode.NotFound)
							{
								ex3 = new ArgumentException(string.Format(GenScriptWizSR.TestFailureMessage, httpWebResponse.ResponseUri, CultureInfo.CurrentCulture));
							}
						}
						else
						{
							ex3 = new ArgumentException(ScriptingEngineResources.ERROR_InvalidWebServiceLogin);
						}
					}
					if (ex3 == null)
					{
						ex3 = ex4;
					}
					this.progressPage.AddActionException(actionIndex, ex3);
				}
				result = OperationStatus.Error;
			}
			catch (NonSupportedCollationException e)
			{
				if (this.isAborted)
				{
					this.UpdateProgressWithAbort();
				}
				else
				{
					int actionIndex2 = this.UpdateProgressStatus(null, ProgressStatus.Error);
					this.progressPage.AddActionException(actionIndex2, e);
				}
				result = OperationStatus.Error;
			}
			catch (Exception e2)
			{
				if (this.isAborted)
				{
					this.UpdateProgressWithAbort();
				}
				else
				{
					int actionIndex3 = this.UpdateProgressStatus(null, ProgressStatus.Error);
					this.progressPage.AddActionException(actionIndex3, e2);
				}
				result = OperationStatus.Error;
			}
			finally
			{
				lock (this.smoConnectionLock)
				{
					this.smoConnection = null;
				}
			}
			this.progressPage.WorkerThreadExiting(result);
		}

		private void ScriptProgressEvent(object sender, ProgressEventArgs e)
		{
			if (this._actions.Count > this._actionIndex && string.Compare(this._actions[this._actionIndex], e.Status.Trim(), StringComparison.CurrentCulture) == 0)
			{
				if (this._actionIndex > 0)
				{
					if (this.hasObjectInformation)
					{
						this.progressPage.UpdateActionStatus(this.currentStep++, ProgressStatus.SuccessWithInfo);
						this.hasObjectInformation = false;
					}
					else
					{
						this.progressPage.UpdateActionStatus(this.currentStep++, ProgressStatus.Success);
					}
				}
				this.progressPage.UpdateActionStatus(this.currentStep, ProgressStatus.InProgress);
				this._actionIndex++;
				return;
			}
			if (e.EventType == ProgressEventType.ObjectInformation)
			{
				this.hasObjectInformation = true;
				this.progressPage.AddActionInfoString(this.currentStep, e.Status);
				return;
			}
			if (e.EventType == ProgressEventType.WritingObject)
			{
				this.progressPage.UpdateActionStatus(this.currentStep, ProgressStatus.InProgress);
				this.progressPage.UpdateActionDescription(this.currentStep, e.Status);
			}
		}

		private void UpdateProgressWithAbort()
		{
			string scriptingCancled = GenScriptWizSR.ScriptingCancled;
			int actionIndex = this.UpdateProgressStatus(null, ProgressStatus.Error);
			this.progressPage.UpdateActionStatus(0, ProgressStatus.SuccessWithInfo);
			this.progressPage.AddActionInfoString(actionIndex, scriptingCancled);
		}

		private void UpdateProgressFromSmoException(SmoException e, object failedObject)
		{
			Urn urn = null;
			SqlSmoObject sqlSmoObject = failedObject as SqlSmoObject;
			if (sqlSmoObject != null)
			{
				urn = sqlSmoObject.Urn;
			}
			int actionIndex = this.UpdateProgressStatus(urn, ProgressStatus.Error);
			this.progressPage.AddActionException(actionIndex, e);
		}

		private void WatchAbortThread()
		{
			Thread thread = new Thread(new ThreadStart(this.Script));
			thread.Start();
			while (thread.IsAlive)
			{
				Thread.Sleep(200);
				if (this.progressPage.IsAborted)
				{
					this.isAborted = true;
					lock (this.smoConnectionLock)
					{
						if (this.smoConnection != null)
						{
							this.smoConnection.Cancel();
						}
					}
					thread.Abort();
					thread.Join();
					this.progressPage.WorkerThreadExiting(OperationStatus.Aborted);
				}
			}
		}

		internal void SetProgressAbort(bool enabled)
		{
			this.progressPage.AllowAbort = enabled;
		}

		protected override void OnInitializeProgressPage()
		{
			this.generalData = (GenWizGeneralData)base.WizardInputs.FindItem(0);
			this.dataContainer = this.generalData.DataContainer;
			this.hasObjectInformation = false;
			if (!this.generalData.ServerObject.Databases.Contains(this.generalData.DatabaseName))
			{
				string message = GenScriptWizSR.GenerateScriptDBNotFound(this.generalData.DatabaseName);
				ArgumentException ex = new ArgumentException(message);
				throw ex;
			}
			this.scriptMaker = new GenerateScriptMaker(this);
			this.progressPage.Title = GenScriptWizSR.GenerateScriptProgressTitle;
			this.progressPage.SubTitle = GenScriptWizSR.GenerateScriptProgressSubTitle;
			this.progressPage.ShowBackOnIncompleteOperation = true;
			this.progressPage.ActionUpdateEnabled = true;
			this.progressPage.AllowAbort = true;
			this._actions = new List<string>();
			this.progressPage.AddAction(ScriptingEngineResources.IncludeDefaultObjects);
			this.isAborted = false;
			this.progressPage.WorkerThreadStart = new ThreadStart(this.Script);
			this.progressPage.WorkerThreadStart = new ThreadStart(this.WatchAbortThread);
		}

		internal void OnScriptingError(object sender, Microsoft.SqlServer.Management.SqlManagerUI.Scripting.ScriptingErrorEventArgs e)
		{
			Thread.Sleep(10);
			this.UpdateProgressStatus(e.Current, ProgressStatus.Error);
			this.progressPage.AddActionException(this.currentStep, e.Error);
			GenWizOptionsBase genWizOptionsBase = (GenWizOptionsBase)base.WizardInputs.FindItem(1);
			e.ContinueScripting = genWizOptionsBase.ContinueScriptingOnError;
		}

		internal void OnProgressReport(object sender, ScriptingProgressEventArgs args)
		{
			Thread.Sleep(10);
			this.UpdateProgressStatus(args.Current, ProgressStatus.Success);
		}

		internal int UpdateProgressStatus(Urn urn, ProgressStatus status)
		{
			bool flag = true;
			if (urn != null)
			{
			}
			if (flag)
			{
				this.progressPage.UpdateActionStatus(this.currentStep, status);
			}
			return this.currentStep;
		}

		internal static void ShowErrorMessageForProvider(IMessageBoxProvider messageProvider, ProviderEntity provider, Exception ex, IWin32Window owner)
		{
			if (ex is WebException && ((WebException)ex).Response is HttpWebResponse)
			{
				HttpWebResponse httpWebResponse = ((WebException)ex).Response as HttpWebResponse;
				HttpStatusCode statusCode = httpWebResponse.StatusCode;
				if (statusCode == HttpStatusCode.Unauthorized)
				{
					messageProvider.ShowMessage(ScriptingEngineResources.ERROR_InvalidWebServiceLogin, GenScriptWizSR.TestTitleFailure, ExceptionMessageBoxButtons.OK, ExceptionMessageBoxSymbol.Warning, owner);
					return;
				}
				if (statusCode == HttpStatusCode.NotFound)
				{
					messageProvider.ShowMessage(string.Format(GenScriptWizSR.TestFailureMessage, provider.WebServiceAddress, CultureInfo.CurrentCulture), GenScriptWizSR.TestTitleFailure, ExceptionMessageBoxButtons.OK, ExceptionMessageBoxSymbol.Warning, owner);
					return;
				}
			}
			messageProvider.ShowMessage(ex, GenScriptWizSR.TestTitleFailure, ExceptionMessageBoxButtons.OK, ExceptionMessageBoxSymbol.Warning, owner);
		}

		private void InitializeComponent()
		{
			this.BackEnabled = true;
			base.ClientSize = new Size(494, 360);
			this.FinishEnabled = true;
			base.Name = "GenScriptWizForm";
		}
	}
}
